#!/usr/bin/env python3
"""
代码备份脚本 - 创建代码文件的完整备份副本
"""

import os
import shutil
import datetime
from pathlib import Path

def create_code_backup():
    """创建代码文件备份到新的目录"""
    # 获取当前时间作为备份目录名的一部分
    timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
    
    # 创建备份目录
    backup_root_dir = "code_backups"
    if not os.path.exists(backup_root_dir):
        os.makedirs(backup_root_dir)
    
    # 创建带时间戳的备份目录
    backup_dir_name = f"fault_management_system_backup_{timestamp}"
    backup_dir_path = os.path.join(backup_root_dir, backup_dir_name)
    
    # 创建备份目录
    os.makedirs(backup_dir_path)
    
    print(f"正在创建代码备份到: {backup_dir_path}")
    
    # 要排除的目录和文件模式
    exclude_dirs = {'__pycache__', '.git', 'backups', 'code_backups', 'temp_restore'}
    exclude_extensions = {'.pyc', '.pyo', '.log'}
    
    # 获取项目根目录的绝对路径，用于更准确地排除备份目录
    project_root = os.path.abspath('.')
    backup_root_abs = os.path.abspath(backup_root_dir)
    
    # 复制文件
    copied_files = 0
    for root, dirs, files in os.walk('.'):
        # 排除特定目录
        dirs[:] = [d for d in dirs if d not in exclude_dirs]
        
        # 特别排除备份目录本身
        dirs[:] = [d for d in dirs if os.path.abspath(os.path.join(root, d)) != backup_root_abs]
        
        # 计算相对路径
        relative_path = os.path.relpath(root, '.')
        
        # 创建目标目录
        if relative_path == '.':
            target_dir = backup_dir_path
        else:
            target_dir = os.path.join(backup_dir_path, relative_path)
            if not os.path.exists(target_dir):
                os.makedirs(target_dir)
        
        # 复制文件
        for file in files:
            # 排除特定扩展名的文件
            if any(file.endswith(ext) for ext in exclude_extensions):
                continue
                
            source_file = os.path.join(root, file)
            target_file = os.path.join(target_dir, file)
            
            # 复制文件
            try:
                shutil.copy2(source_file, target_file)
                copied_files += 1
                print(f"已复制: {source_file}")
            except Exception as e:
                print(f"复制失败 {source_file}: {e}")
    
    print(f"\n代码备份完成!")
    print(f"备份位置: {backup_dir_path}")
    print(f"共复制 {copied_files} 个文件")
    
    return backup_dir_path

def list_code_backups():
    """列出所有代码备份"""
    backup_root_dir = "code_backups"
    if not os.path.exists(backup_root_dir):
        print("没有找到代码备份目录")
        return []
    
    backups = [f for f in os.listdir(backup_root_dir) 
               if os.path.isdir(os.path.join(backup_root_dir, f)) 
               and f.startswith('fault_management_system_backup_')]
    
    backups.sort(reverse=True)  # 按时间倒序排列
    
    if not backups:
        print("没有找到代码备份")
        return []
    
    print("可用的代码备份:")
    for i, backup in enumerate(backups, 1):
        print(f"{i}. {backup}")
    
    return backups

def restore_code_backup(backup_index=None):
    """从代码备份恢复"""
    backups = list_code_backups()
    if not backups:
        return
    
    if backup_index is None:
        try:
            choice = int(input("请输入要恢复的备份编号: "))
            backup_index = choice - 1
        except (ValueError, IndexError):
            print("无效的选择")
            return
    
    if 0 <= backup_index < len(backups):
        backup_name = backups[backup_index]
        backup_path = os.path.join("code_backups", backup_name)
        
        # 确认操作
        confirm = input(f"确定要从代码备份 {backup_name} 恢复吗？这将覆盖当前文件！(y/N): ")
        if confirm.lower() != 'y':
            print("操作已取消")
            return
        
        # 复制备份文件到当前目录
        restored_files = 0
        for root, dirs, files in os.walk(backup_path):
            # 计算相对路径
            relative_path = os.path.relpath(root, backup_path)
            
            # 确定目标目录
            if relative_path == '.':
                target_dir = '.'
            else:
                target_dir = relative_path
                # 创建目标目录（如果不存在）
                if not os.path.exists(target_dir):
                    os.makedirs(target_dir)
            
            # 复制文件
            for file in files:
                source_file = os.path.join(root, file)
                target_file = os.path.join(target_dir, file)
                
                # 复制文件
                try:
                    shutil.copy2(source_file, target_file)
                    restored_files += 1
                    print(f"已恢复: {target_file}")
                except Exception as e:
                    print(f"恢复失败 {target_file}: {e}")
        
        print(f"\n从代码备份恢复完成!")
        print(f"共恢复 {restored_files} 个文件")
    else:
        print("无效的备份编号")

def main():
    """主函数"""
    print("故障管理系统代码备份工具")
    print("1. 创建新的代码备份")
    print("2. 列出所有代码备份")
    print("3. 从代码备份恢复")
    
    choice = input("请选择操作 (1-3): ")
    
    if choice == '1':
        create_code_backup()
    elif choice == '2':
        list_code_backups()
    elif choice == '3':
        restore_code_backup()
    else:
        print("无效选择")

if __name__ == "__main__":
    main()